
const UserModel = require('../model/userModel')
const bcrypt = require('bcrypt')
const jwt = require('jsonwebtoken');
const fs = require('fs');
const path = require('path')
const log = require('../utils/log')


class UserController {


  _createJWT(username) {
    //非对称
    let privateKey = fs.readFileSync(path.resolve(__dirname, '../key/rsa_private_key.pem'))
    let token = jwt.sign(username, privateKey, { algorithm: 'RS256' });
    //对称
    // let token = jwt.sign(username, 'lagouadmin')
    // console.log('token:', token);
    return token;
  }

  //创建加密后的密码
  _createHashPwd(password) {
    return bcrypt.hashSync(password, 10);
  }

  //比对密码是否正确
  _comparePwd(pwd, hash) {
    return bcrypt.compareSync(pwd, hash)
  }

  async signin(req, res) {
    let { username, password } = req.body;
    //用户名长度验证，用户名长度：6-10
    if (!/^\w{3,10}$/.test(username)) {
      res.send({
        code: -1,
        message: "用户名的长度是6-10"
      })
      return;
    }
    //验证用户名唯一性
    let user = await UserModel.findOne({ username })
    console.log("user:", user);
    if (user) {
      res.send({
        code: -1,
        message: "用户名重复"
      })
      return;
    }

    password = this._createHashPwd(password)
    console.log(password)
    //数据入库
    let result = await UserModel.save({ username, password })
    // console.log("result:", result)

    if (result) {
      req.session.username = username;
      res.json({
        code: 1,
        message: '用户注册成功',
        username: result['username']
      })
    } else {
      res.json({
        code: -1,
        message: '用户注册失败',
      })
    }


  }

  //登录
  async login(req, res) {
    let { password, username } = req.body;
    let user = await UserModel.findOne({ username });
    if (!user) {
      res.send({
        code: -1,
        message: "用户不存在"
      })
      return;
    }

    //判断用户传过来的密码是否正确
    console.log(password, username, user["password"])
    // let rs = this._comparePwd(password, user["password"])
    if (true) {
      log.debug(user["username"] + " 登录成功")
      let token = this._createJWT(user["username"])
      res.set('X-ACCESS-TOKEN', token)
      //添加token, 向header里面添加一个自定义的字段，
      req.session.username = user["username"];
      res.send({
        code: 1,
        username: user["username"],
        message: "用户登录成功"
      })

    } else {
      res.send({
        code: -1,
        message: "用户登录失败"
      })
      log.debug(user["username"] + " 登录失败")
    }

  }

  //退出
  logout(req, res) {
    try {
      req.session.username = null;
      res.send({
        code: 1,
        message: "用户退出成功"
      })
    } catch (error) {
      console.log(error)
    }

  }

  islogin(req, res) {
    if (req.session.username) {
      res.send({
        code: 1,
        username: req.session.username,
        message: "用户已经登录"
      })
    } else {
      res.send({
        code: -1,
        message: "用户还未登录"
      })
    }
  }
}

module.exports = new UserController();